﻿using System;

namespace VirtualTournaments.Business.Tournaments
{
	public class Match : ICompetition
	{
		private Tournament _tournament;
		private Team _local;
		private Team _visitor;
		private bool _played;
		private MatchResult _result;

		protected static Random RANDOM = new Random();
		protected const double GOAL_PROBABILITY = 0.5;

		public Match(Tournament tournament, Team local, Team visitor)
		{
			this._tournament = tournament;
			this._local = local;
			this._visitor = visitor;
			IsPlayed = false;
		}

		public virtual Tournament Tournament
		{
			get { return _tournament; }
			protected set { _tournament = value; }
		}

		public virtual Team Local
		{
			get { return _local; }
			protected set { _local = value; }
		}

		public virtual Team Visitor
		{
			get { return _visitor; }
			protected set { _visitor = value; }
		}

		public bool IsPlayed
		{
			get { return _played; }
			protected set { _played = value; }
		}

		public MatchResult Result
		{
			get { return _result; }
			protected set { _result = value; }
		}

		public virtual MatchResult Play()
		{
			if (!IsPlayed)
			{
				byte localGoals = 0;
				byte visitorGoals = 0;

				while (RANDOM.NextDouble() < GOAL_PROBABILITY)
					localGoals++;
				while (RANDOM.NextDouble() < GOAL_PROBABILITY)
					visitorGoals++;
				Result = new MatchResult(Local, Visitor, localGoals, visitorGoals);

			}
			return Result;
		}

		public override String ToString()
		{
			return String.Concat(Local.Name, " - ", Visitor.Name);
		}

		public bool HasFinished()
		{
			return IsPlayed;
		}
	}
}
